package com.test.mchelepesa.util_rice.http_rice;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.ThreadUtil_rice;
import com.test.mchelepesa.util_rice.analytics_rice.util_rice.AnalyticsUtil_rice;
import com.test.mchelepesa.util_rice.data.Demo_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseApplication_rice;
import com.test.mchelepesa.util_rice.event_points.TrackManager_rice;
import com.test.mchelepesa.util_rice.helper_rice.UserInfoHelper_rice;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.constant_rice.Constant_rice;
import com.test.mchelepesa.constant_rice.Url_rice;
import com.test.mchelepesa.util_rice.http_rice.connection.DeviceHttpConnection;
import com.test.mchelepesa.util_rice.http_rice.connection.BusinessHttpConnection;
import com.test.mchelepesa.util_rice.http_rice.connection.PointHttpConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Objects;
import java.util.TreeMap;

import static com.test.mchelepesa.constant_rice.Url_rice.PATH_QUERY_DEVICE_INFO_TYPES;
import static com.test.mchelepesa.constant_rice.Url_rice.PATH_USER_BURIED_POINT_FOR_BATCH;
import static com.test.mchelepesa.constant_rice.Url_rice.Url;

public class HttpManager_rice {

    private final HttpLogger_rice httpLogger = new HttpLogger_rice();

    private HttpManager_rice() {}

    private static class Inner {
        private static final HttpManager_rice instance = new HttpManager_rice();
    }

    public static HttpManager_rice getInstance() {
        return Inner.instance;
    }

    public static int RequestFailedCount = 0;

    //处理响应
    private void handleResponse(String lastWord, JSONObject responseJson) {
        ThreadUtil_rice.getInstance().runOnUiThread(() -> HttpPresenter_rice.getInstance().notifyActivityHandleResponse(lastWord, responseJson));
    }

    //获取初始化JSON对象
    @NonNull
    private JSONObject getRequestJson() {
        return getRequestJson(new JSONObject());
    }

    private JSONObject getRequestJson(JSONObject jsonObject) {
        try {
            jsonObject.put("isLimitAdTrackingEnabled", AnalyticsUtil_rice.INSTANCE.getAdEnabled() + "");
            jsonObject.put("aduid", AnalyticsUtil_rice.INSTANCE.getAdId());
            jsonObject.put("aduidPath", AnalyticsUtil_rice.INSTANCE.getAndroidId());
            jsonObject.put("version", BaseApplication_rice.gApplication_rice().getVersionCodeStr());
            jsonObject.put("token", UserInfoHelper_rice.getInstance().getToken_rice().trim());
            jsonObject.put("androidId", AnalyticsUtil_rice.INSTANCE.getAndroidId());
            jsonObject.put("userId", UserInfoHelper_rice.getInstance().getUserId_rice().trim());
            jsonObject.put("advertId", AnalyticsUtil_rice.INSTANCE.getAdId());
            jsonObject.put("product", Constant_rice.PRODUCT.trim());
            jsonObject.put("clientType", Constant_rice.CLIENT.trim());
            jsonObject.put("apiVersion", "v3");
            jsonObject.put("localTimestamp", String.valueOf(System.currentTimeMillis()));
            jsonObject.put("language", HttpPresenter_rice.getInstance().getLanguage());

            return jsonObject;
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }
        return jsonObject;
    }

    //发送请求
    public void request(String lastWord, String jsonString) {
        requestWithoutCountryPrefix(StaticConfig_rice.getCountryUrlPrefix() + lastWord, jsonString);
    }

    //发送请求（不带国家前缀）
    private void requestWithoutCountryPrefix(String lastWord, String jsonString) {

        String wholeUrl = Url + lastWord;

        // 切回主线程显示loading dialog
        ThreadUtil_rice.getInstance().runOnUiThread(() -> HttpPresenter_rice.getInstance().progressBarDialogShow());

        BusinessHttpConnection businessHttpConnection = new BusinessHttpConnection(wholeUrl, jsonString);

        httpLogger.log("request-" + wholeUrl, jsonString);

        // 它会开启一个子线程，执行方法内容
        businessHttpConnection.fetch("POST", body -> {

            httpLogger.log("response-" + wholeUrl, body);

            HttpPresenter_rice.getInstance().progressBarDialogDismiss();

            try {
                String word = StringUtil_rice.getUrlSuffix(wholeUrl);
                handleResponse(word, new JSONObject(body));
            } catch (JSONException e) {
                StringUtil_rice.printException(e);
            }

            return null;
        }, (integer, s) -> {

            HttpPresenter_rice.getInstance().progressBarDialogDismiss();

            RequestFailedCount++;

            if (RequestFailedCount<4){
                HttpPresenter_rice.getInstance().showReloadDialog(() -> requestWithoutCountryPrefix(lastWord,jsonString));
            }else {
                RequestFailedCount=0;
                HttpPresenter_rice.getInstance().showReloadDialog2(() -> requestWithoutCountryPrefix(lastWord,jsonString));
            }

            return null;
        }, false);
    }

    public void requestSilent(String wholeUrl, String jsonString) {

        if (TextUtils.isEmpty(wholeUrl)) return;

        PointHttpConnection pointHttpConnection = new PointHttpConnection(wholeUrl, jsonString);

        httpLogger.log("request-" + wholeUrl, jsonString);

        pointHttpConnection.fetch(true);
    }

    public void requestDevice(String wholeUrl, String jsonString) {

        if (TextUtils.isEmpty(wholeUrl)) return;

        DeviceHttpConnection deviceConnection = new DeviceHttpConnection(wholeUrl, jsonString);

        httpLogger.log("request-" + wholeUrl, jsonString);

        deviceConnection.fetch(true);
    }

    //global信息
    public void queryGlobal() {
        requestWithoutCountryPrefix(Url_rice.PATH_GLOBAL, getRequestJson().toString());
    }

    //获取App配置
    public void getAppShowInfo() {
        request(Url_rice.PATH_APP_SHOW_INFO, getRequestJson().toString());
    }

    //注册登录
    public void userLogin(String phoneNum) {
        UserInfoHelper_rice.getInstance().setMobile_rice(StringUtil_rice.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_rice.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_rice.INSTANCE.getInstallReferrer());
            jsonObject.put("code", "0000");
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("notBindWalletFlag", "YES");
            jsonObject.put("directLoginFlag", "YES");
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }
        request(Url_rice.PATH_LOGIN_NO_CODE, jsonObject.toString());
    }

    public void submitServiceFeedback(String type, String opinion) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("type", type);
            jsonObject.put("opinion", opinion);
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }
        request(Url_rice.PATH_FEED_BACK, jsonObject.toString());
    }

    //获取银行列表（尼日）
    public void fetchBankCodes_Niri() {
        request(Url_rice.PATH_FETCH_BANK_CODE, getRequestJson().toString());
    }

    //获取钱包列表（科特）
    public void fetchBankAccount() {
        request(Url_rice.PATH_FETCH_BOUND_BANK_ACCOUNT, getRequestJson().toString());
    }

    //新增钱包（科特）
    public void bindBankAccount(String walletMobile, String walletMobileConfirm, String walletChannel) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("walletMobile", walletMobile);
            jsonObject.put("walletMobileConfirm", walletMobileConfirm);
            jsonObject.put("walletChannel", walletChannel);
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }
        request(Url_rice.PATH_BIND_BANK_ACCOUNT, jsonObject.toString());
    }

    //删除钱包（科特）
    public void deleteBoundBankAccount(String ids) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("ids", ids);
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }
        request(Url_rice.PATH_DELETE_BOUND_BANK_ACCOUNT, jsonObject.toString());
    }

    //请求用户流程状态
    public void requestUserProcess() {
        request(Url_rice.PATH_USER_PROCESS, getRequestJson().toString());
    }

    //上传用户信息
    public void uploadInfo(String url, TreeMap<String, String> dataMap) {
        try {
            JSONObject jsonObject = getRequestJson();
            for (String k : dataMap.keySet()) {
                String key = StringUtil_rice.getSafeString(k);
                String value = StringUtil_rice.getSafeString(dataMap.get(k));
                jsonObject.put(key, value);
            }
            StaticConfig_rice.Upload_Info_Url = url;
            String prefix = StaticConfig_rice.getCountryUrlPrefix();
            if (!url.startsWith(prefix)) url = prefix + url;
            requestWithoutCountryPrefix(url, jsonObject.toString());
        } catch (Exception e) {
            StringUtil_rice.printException(e);
        }
    }

    //请求额度列表
    public void queryLoanLimit() {
        request(Url_rice.PATH_LOAN_LIMIT, getRequestJson().toString());
    }

    //请求借款申请页信息/贷款详情
    public void requestLoanApplyDetail() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("localLanguage",
                    "sw".equalsIgnoreCase(UserInfoHelper_rice.getInstance().getLanguage()) ? "YES" : "NO");
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }
        request(Url_rice.PATH_GET_LOAN_APPLY_DETAIL, getRequestJson(jsonObject).toString());
    }

    //发起借款申请
    public void loanApply() {
        request(Url_rice.PATH_LOAN_APPLY, getRequestJson().toString());
    }

    //获取还款信息
    public void getRepayDetail() {
        request(Url_rice.PATH_REPAY_INFO, getRequestJson().toString());
    }

    //获取还款H5（加纳、科特、越南）
    public void orderRepayH5_gh_cl_vi() {
        request(Url_rice.PATH_ORDER_REPAY_H5, getRequestJson().toString());
    }

    //获取还款H5（乌干达、肯尼亚）
    public void orderRepayH5_ug_ke() {
        request(Url_rice.PATH_GET_ORDER_REPAY_H5, getRequestJson().toString());
    }

    //初始化paystack订单（尼日）
    public void orderRepaySDK(String cardNumber, String expiryYear, String expiryMonth, String cvv) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cardNumber", cardNumber.trim());
            jsonObject.put("expiryYear", expiryYear.trim());
            jsonObject.put("expiryMonth", expiryMonth.trim());
            jsonObject.put("cvv", cvv.trim());
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }
        request(Url_rice.PATH_ORDER_REPAY_SDK, getRequestJson(jsonObject).toString());
    }

    //获取paystack卡列表（尼日）
    public void bankList_niri() {
        request(Url_rice.PATH_BANK_LIST, getRequestJson().toString());
    }

    //线下还款-创建虚拟账号还款
    public void createVirtualAccount() {
        request(Url_rice.PATH_CREATE_VIRTUAL_ACCOUNT, getRequestJson().toString());
    }

    /**
     * 上传图片
     */
    public void uploadImage(String filePath_equitable) {

        final String uplodUrl_equitable = StaticConfig_rice.getBaseUrl() + StaticConfig_rice.getCountryUrlPrefix() + Url_rice.PATH_UPLOAD_IMAGE_FILE;

        if (Looper.myLooper() != Looper.getMainLooper())
            ThreadUtil_rice.getInstance().runOnUiThread(() -> HttpPresenter_rice.getInstance().progressBarDialogShow());
        else HttpPresenter_rice.getInstance().progressBarDialogShow();

        try {
            if (!TextUtils.isEmpty(filePath_equitable)) {
                final File imageFile_equitable = new File(filePath_equitable);

                if (imageFile_equitable.isFile()) {

                    ThreadUtil_rice.getInstance().runOnChildThread(() -> {
                        BusinessHttpConnection businessHttpConnection = new BusinessHttpConnection(uplodUrl_equitable, "");
                        businessHttpConnection.uploadFile(filePath_equitable, body -> {
                            ThreadUtil_rice.getInstance().runOnUiThread(() -> HttpPresenter_rice.getInstance().progressBarDialogDismiss());
                            try {
                                final String word = StringUtil_rice.getUrlSuffix(uplodUrl_equitable);
                                handleResponse(word, new JSONObject(body));
                            } catch (JSONException e) {
                                StringUtil_rice.printException(e);
                            }

                            return null;
                        }, (integer, s) -> {
                            HttpPresenter_rice.getInstance().showToastOnUiThread(s);
                            ThreadUtil_rice.getInstance().runOnUiThread(() -> HttpPresenter_rice.getInstance().progressBarDialogDismiss());
                            if (Constant_rice.Debug) Log.e("Request Fail", s);
                            return null;
                        });
                    });
                }
            }
        } catch (Exception e) {
            StringUtil_rice.printException(e);
        }

    }

    //获取评分弹窗信息
    public void fetchStarWindowConfig() {
        request(Url_rice.PATH_FETCH_STAR_WINDOW_CONFIG, getRequestJson().toString());
    }

    public void uploadSefieInfo(String faceUrl, boolean deleteData) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("faceImgUrl", faceUrl);
            jsonObject.put("deleteDataFlag", deleteData ? "YES" : "NO");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        request(Url_rice.PATH_OCR_INFO, getRequestJson(jsonObject).toString());
    }


    public void uploadOcrInfo(String cardType, String frontImgUrl, String backImgUrl, boolean deleteData) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cardImgUrl", frontImgUrl);
            jsonObject.put("cardBackImgUrl", StringUtil_rice.getSafeString(backImgUrl));
            jsonObject.put("cardType", cardType);
            jsonObject.put("deleteDataFlag", deleteData ? "YES" : "NO");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        request(Url_rice.PATH_OCR_INFO, getRequestJson(jsonObject).toString());
    }

    public void sendWhatsAppCode(String mobile, String type) {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("mobile", UserInfoHelper_rice.getInstance().getMobil_rice());
            jsonObject.put("submitMobile", StringUtil_rice.getSafeString(mobile));
            jsonObject.put("sendType", StringUtil_rice.getSafeString(type));
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }

        request(Url_rice.PATH_SEND_WHATSAPP_MESSAGE, getRequestJson(jsonObject).toString());

    }

    public void checkWhatsAppCode(String mobile, String type, String code) {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("mobile", StringUtil_rice.getSafeString(mobile));
            jsonObject.put("submitMobile", StringUtil_rice.getSafeString(mobile));
            jsonObject.put("code", StringUtil_rice.getSafeString(code));
            jsonObject.put("checkType", StringUtil_rice.getSafeString(type));
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }

        request(Url_rice.PATH_CHECK_WHATSAPP_CODE, getRequestJson(jsonObject).toString());

    }

    public void fetchDropConfig() {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("type", "GET");
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }

        UserInfoHelper_rice.getInstance().sDropType("GET");

        request(Url_rice.PATH_DROP_USER_DATA, getRequestJson(jsonObject).toString());

    }

    public void dropUserData() {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("type", "DROP");
        } catch (JSONException e) {
            StringUtil_rice.printException(e);
        }

        UserInfoHelper_rice.getInstance().sDropType("DROP");

        request(Url_rice.PATH_DROP_USER_DATA, getRequestJson(jsonObject).toString());

    }

    /**
     * 保存页面显示/隐藏打点
     */
    public void saveUserBuriedPoint(String pageEvent) {
        TrackManager_rice.INSTANCE.track(pageEvent.toUpperCase(),"");
    }

    /**
     * 保存页面显示/隐藏打点
     */
    public void saveUserBuriedPoint(String pageEvent, String remark) {
        TrackManager_rice.INSTANCE.track(pageEvent.toUpperCase(),remark);
    }

    /**
     * 保存页面显示/隐藏打点 并上传
     */
    public void saveUserBuriedPointAndUpload(String pageEvent) {
        TrackManager_rice.INSTANCE.trackAndUpload(pageEvent.toUpperCase(),"");
    }

    /**
     * 保存页面显示/隐藏打点 并上传
     */
    public void saveUserBuriedPointAndUpload(String pageEvent, String remark) {
        TrackManager_rice.INSTANCE.trackAndUpload(pageEvent.toUpperCase(),remark);
    }

    public void queryDeviceInfoTypes() {

        String wholeUrl = Url+ StaticConfig_rice.getCountryUrlPrefix() + PATH_QUERY_DEVICE_INFO_TYPES;

        String jsonString = getRequestJson().toString();

        BusinessHttpConnection businessHttpConnection = new BusinessHttpConnection(wholeUrl, jsonString);

        httpLogger.log("request-" + wholeUrl, jsonString);

        // 它会开启一个子线程，执行方法内容
        businessHttpConnection.fetch("POST", body -> {

            httpLogger.log("response-" + wholeUrl, body);

            if (TextUtils.isEmpty(body)) return null;

            try {

                JSONArray jsonArray = Objects.requireNonNull(new JSONObject(body).optJSONObject("obj")).optJSONArray("deviceInfoTypes");
                ArrayList<String> list = new ArrayList<>();
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        list.add(jsonArray.optString(i));
                    }
                }
                new Demo_rice(BaseApplication_rice.gApplication_rice()).upload(list);

            } catch (Exception e) {
                StringUtil_rice.printException(e);
            }

            return null;
        }, (integer, s) -> {

            new Demo_rice(BaseApplication_rice.gApplication_rice()).upload(new ArrayList<String>(){{
                add("T1");
                add("T2");
                add("T3");
                add("T4");
                add("T5");
                add("T6");
                add("T7");
            }});

            return null;
        }, false);
    }

    public void uploadEvents(JSONArray jsonArray, Runnable onSuccess){

        if (jsonArray==null) return;

        if (Constant_rice.Debug){
            Log.i("event-size", String.valueOf(jsonArray.length()));
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                if (jsonObject != null)
                    Log.i("event_detail", "id=" + jsonObject.optString("id") + ", type=" + jsonObject.optString("type") + ", remark=" + jsonObject.optString("remark"));
            }
        }

        String wholeUrl = Url+ StaticConfig_rice.getCountryUrlPrefix() + PATH_USER_BURIED_POINT_FOR_BATCH;

        JSONObject jsonObject = getRequestJson();

        try {
            jsonObject.put("list",jsonArray);
        }catch (Exception e){
            StringUtil_rice.printException(e);
        }

        BusinessHttpConnection businessHttpConnection = new BusinessHttpConnection(wholeUrl, jsonObject.toString());

        httpLogger.log("request-" + wholeUrl, jsonObject.toString());

        // 它会开启一个子线程，执行方法内容
        businessHttpConnection.fetch("POST", body -> {

            try {
                if (!TextUtils.isEmpty(body)){
                    httpLogger.log("response-"+wholeUrl,body);
                    JSONObject responseJson = new JSONObject(body);
                    if (responseJson.has("code") && Integer.parseInt(responseJson.optString("code"))==0 && onSuccess!=null){
                        onSuccess.run();
                    }
                }
            }catch (Exception e){
                StringUtil_rice.printException(e);
            }
            return null;
        }, (integer, s) -> null, false);

    }

}
